package xquery;

import java.util.ArrayList;

import org.w3c.dom.Node;

public class XQuerySomeCond extends XQueryCond {
	XQVarExpPair[] someclause;
	XQExpression satisfiesclause;
	
	@Override
	public XPathData eval(XQContext context, ArrayList<Node> currentNodeList) {
		context.openContext();
		
		boolean result = evalSome(0,context,currentNodeList);
		
		context.closeContext();
		
		return new XPathData(result);
	}

	boolean evalSome(int i, XQContext context, ArrayList<Node> currentNodeList) {
		if(i==someclause.length) {
			if(satisfiesclause.eval(context, currentNodeList).getBool())
				return true;
			else
				return false;
		}
		
		String var = someclause[i].var;
		XQExpression exp = someclause[i].exp;
		ArrayList<Node> expResult = exp.eval(context, currentNodeList).getList();

		for (Node n : expResult) {
			ArrayList<Node> list = new ArrayList<Node>();
			list.add(n);
			context.put(var, new XPathData(list));

			if(evalSome(i + 1, context, currentNodeList))
				return true;
		}
		
		return false;
	}

}
